package com.egdigital.allzic.adswizz;

import java.io.BufferedInputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import android.content.Context;
import android.os.AsyncTask;

import com.egdigital.allzic.adswizz.XMLDownloader.DownloadStatus;
import com.egdigital.allzic.utils.NetworkManager;

/**
 * {@link AsyncTask} that manages the download of xml datas and gives feedback through {@link OnXMLDownloadListener} interface<br>
 * <b>see also</b> <br>
 * {@link SAXParser}, {@link SAXParserFactory}
 */
public class XMLDownloader extends AsyncTask<Context, Void, DownloadStatus> {

	private static final String		TAG	= XMLDownloader.class.getSimpleName();	// log
	private String					mURL;
	private HashMap<String, String>	mData;
	private OnXMLDownloadListener	mListener;

	/**
	 * <code>enum</code> definition to distinct download results : <br>
	 * <li><code>STATUS_OK</code> the download finished without any problems</li> <li><code>STATUS_FAILED</code> the download failed before getting all the datas</li> <li><code>STATUS_NOK</code> the
	 * download did not start (no network)</li>
	 */
	public static enum DownloadStatus {
		STATUS_OK, STATUS_FAILED, STATUS_NOK,
	}

	public XMLDownloader(String url, OnXMLDownloadListener listener) {
		mURL = url;
		mListener = listener;
	}

	@Override
	protected void onPreExecute() {
		super.onPreExecute();
	}

	@Override
	protected DownloadStatus doInBackground(Context... params) {
		if (NetworkManager.isConnected(params[0])) {// test network connexion
			SAXParserFactory fabrique = SAXParserFactory.newInstance();
			XMLHandler handler = new XMLHandler();
			try {
				URL url = new URL(mURL);
				HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
				InputStream input = new BufferedInputStream(urlConnection.getInputStream());
				SAXParser parseur = fabrique.newSAXParser();
				parseur.parse(input, handler);// parse xml stream into usable datas
			} catch (Exception e) {
				return DownloadStatus.STATUS_FAILED;
			}
			mData = handler.getResults(); // get result datas
			return DownloadStatus.STATUS_OK;
		} else {
			return DownloadStatus.STATUS_NOK;
		}
	}

	@Override
	protected void onPostExecute(DownloadStatus result) {
		switch (result) {
			case STATUS_OK:
				mListener.OnDownloadFinish(mData);
				break;
			case STATUS_FAILED:
				mListener.OnDownloadFailed();
				break;
			case STATUS_NOK:
				mListener.OnDownloadNoNetwork();
				break;
		}
		super.onPostExecute(result);
	}
}
